<template>
  <div class="content">
    <el-card style="height: 100%">
      <el-form :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地市字段">
              <el-select v-model="form.areaColumn" placeholder="请选择" clearable>
                <el-option v-for="item in conditionList" :key="item.id" :label="item.comment" :value="item.column" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据权限">
              <el-radio-group v-model="form.openLevel">
                <el-radio label="1">私人</el-radio>
                <el-radio label="2">本角色</el-radio>
                <el-radio label="3">公开</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="box">
        <div style="display: flex; height: calc(100% - 50px); padding: 0 10px">
          <el-table
            :data="indexTree"
            border
            height="100%"
            row-key="id"
            :header-cell-style="{ background: '#F5F7FA' }"
            empty-text="请添加行"
            default-expand-all
          >
            <el-table-column prop="indexName">
              <template #header>
                <div style="text-align: center">指标</div>
              </template>
              <template #default="scope">
                <span>{{ scope.row.indexName }}</span>
                <span style="position: absolute; right: 10px">
                  <el-tooltip content="添加子列" placement="top">
                    <el-icon class="cursor" :size="20" color="#67C23A" @click="tableRowAdd(scope.row)">
                      <Plus />
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip content="编辑列" placement="top">
                    <el-icon
                      class="cursor"
                      style="margin-left: 10px"
                      :size="20"
                      color="#409EFF"
                      @click="tableRowEdit(scope.row)"
                    >
                      <Edit />
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip content="添加条件" placement="top">
                    <el-icon
                      class="cursor"
                      style="margin-left: 10px"
                      :size="20"
                      :color="scope.row.condition ? '#409EFF' : '#888'"
                      @click="handleAddCondition(scope.row)"
                    >
                      <Filter />
                    </el-icon>
                  </el-tooltip>
                  <el-tooltip content="删除列" placement="top">
                    <el-icon
                      class="cursor"
                      style="margin-left: 10px"
                      :size="20"
                      color="red"
                      @click="tableRowDel(scope.row)"
                    >
                      <Delete />
                    </el-icon>
                  </el-tooltip>
                </span>
              </template>
            </el-table-column>
            <TableColumn
              v-for="item in headerTree"
              :key="item.id"
              :column="item"
              @add="tableColumnAdd"
              @edit="tableColumnEdit"
              @delete="tableColumnDel"
              @condition="tableColumnCondition"
            />
          </el-table>
          <el-button type="primary" style="margin-left: 20px" @click="handleAddColumn">添加列</el-button>
        </div>
        <el-button type="primary" style="margin-top: 10px" @click="handleAddRow">添加行</el-button>
      </div>
      <div style="position: absolute; bottom: 30px; left: 50%; transform: translateX(-50%)">
        <el-button @click="router.back()">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-card>

    <el-dialog title="列" v-model="columnDialogVisible" width="30%">
      <el-form ref="columnFormRef" :model="columnForm" label-width="80px" :rules="columnRules">
        <el-form-item label="列名" prop="indexName">
          <el-input v-model="columnForm.indexName" />
        </el-form-item>
        <el-form-item label="指标类型" prop="indexType">
          <el-radio-group v-model="columnForm.indexType">
            <el-radio label="1">计算</el-radio>
            <el-radio label="2">非计算</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="columnForm.indexType == '1'">
          <el-form-item label="计算类型" prop="content.computeType">
            <el-radio-group v-model="columnForm.content.computeType">
              <el-radio label="1">求值</el-radio>
              <el-radio label="2">同比</el-radio>
              <el-radio label="3">环比</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="值类型" prop="content.valueType">
            <el-radio-group v-model="columnForm.content.valueType">
              <el-radio label="1">sum（求和）</el-radio>
              <el-radio label="2">avg（平均值）</el-radio>
              <el-radio label="3">count（求数）</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="计算字段" prop="content.valueColumn">
            <el-select v-model="columnForm.content.valueColumn" placeholder="请选择" clearable>
              <el-option v-for="item in conditionList" :key="item.id" :label="item.comment" :value="item.column" />
            </el-select>
          </el-form-item>
          <template v-if="columnForm.content.computeType == '2'">
            <el-form-item label="时间字段" prop="content.YOYColumn">
              <el-select v-model="columnForm.content.YOYColumn" placeholder="请选择" clearable>
                <el-option v-for="item in conditionList" :key="item.id" :label="item.comment" :value="item.column" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="content.YOYStart">
              <el-date-picker
                style="width: 100%"
                v-model="columnForm.content.YOYStart"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="content.YOYEnd">
              <el-date-picker
                style="width: 100%"
                v-model="columnForm.content.YOYEnd"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              />
            </el-form-item>
          </template>
          <template v-if="columnForm.content.computeType == '3'">
            <el-form-item label="时间字段" prop="content.QOQColumn">
              <el-select v-model="columnForm.content.QOQColumn" placeholder="请选择" clearable>
                <el-option v-for="item in conditionList" :key="item.id" :label="item.comment" :value="item.column" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="content.QOQStart">
              <el-date-picker
                style="width: 100%"
                v-model="columnForm.content.QOQStart"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="content.QOQEnd">
              <el-date-picker
                style="width: 100%"
                v-model="columnForm.content.QOQEnd"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              />
            </el-form-item>
          </template>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="columnDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddColumnConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="条件" v-model="isShowCondition" width="60%">
      <Condition ref="conditionRef" :fieldList="conditionList" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowCondition = false">取 消</el-button>
          <el-button type="primary" @click="handleConditionConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="行" v-model="rowDialogVisible" width="30%">
      <el-form ref="columnFormRef" :model="rowForm" label-width="80px" :rules="rowRules">
        <el-form-item label="行名" prop="indexName">
          <el-input v-model="rowForm.indexName" />
        </el-form-item>
        <el-form-item label="指标类型" prop="indexType">
          <el-radio-group v-model="rowForm.indexType">
            <el-radio label="1">计算</el-radio>
            <el-radio label="2">非计算</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rowDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddRowConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { CirclePlus, CircleClose, Delete, Plus, Edit, Filter } from '@element-plus/icons-vue'
import { nextTick, onMounted, reactive } from 'vue'
import TableColumn from './tableColumn.vue'
import Condition from './condition.vue'
import { getNowData, getDataById } from '@/api/analysis'
import { getStatisticsSave, getStatisticsInfo } from '@/api/statistics'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const form = reactive({
  name: '',
  areaColumn: '',
  openLevel: '1'
})
const dataId = ref('')
const headerTree = ref([])
const indexTree = ref([])
const columnDialogVisible = ref(false)
const rowDialogVisible = ref(false)
const isShowCondition = ref(false)
const conditionList = ref([])
const columnForm = reactive({
  indexName: '',
  indexType: '2',
  content: {
    computeType: '1',
    valueType: '1',
    valueColumn: '',
    QOQColumn: '',
    QOQStart: '',
    QOQEnd: '',
    YOYColumn: '',
    YOYStart: '',
    YOYEnd: ''
  }
})
const columnRules = reactive({
  indexName: [{ required: true, message: '请输入', trigger: 'blur' }]
})
const rowForm = reactive({
  indexName: '',
  indexType: '1'
})
const rowRules = reactive({
  indexName: [{ required: true, message: '请输入', trigger: 'blur' }]
})
const columnFormRef = ref(null)
const conditionRef = ref(null)
const addPColumn = ref('')
const addPRow = ref('')
const handleAddColumn = () => {
  addPColumn.value = ''
  columnDialogVisible.value = true
}
const handleAddColumnConfirm = () => {
  columnFormRef.value.validate((valid) => {
    if (valid) {
      findAndEdit(columnForm)
      addPColumn.value = ''
      resetColumnForm()
      columnDialogVisible.value = false
    }
  })
}
const resetColumnForm = () => {
  columnForm.indexName = ''
  columnForm.indexType = '2'
  columnForm.content.computeType = '1'
  columnForm.content.valueType = '1'
  columnForm.content.valueColumn = ''
  columnForm.content.QOQColumn = ''
  columnForm.content.QOQStart = ''
  columnForm.content.QOQEnd = ''
  columnForm.content.YOYColumn = ''
  columnForm.content.YOYStart = ''
  columnForm.content.YOYEnd = ''
  delete columnForm.id
}
const tableColumnAdd = (data) => {
  console.log(data)
  resetColumnForm()
  addPColumn.value = data
  columnDialogVisible.value = true
}
const tableColumnEdit = (data) => {
  addPColumn.value = data
  Object.assign(columnForm, JSON.parse(JSON.stringify(data)))
  columnDialogVisible.value = true
}
const tableColumnDel = (data) => {
  addPColumn.value = data
  findAndEdit(data, 'del')
  addPColumn.value = ''
}
const tableColumnCondition = (data) => {
  isShowCondition.value = true
  nextTick(() => {
    conditionRef.value.reset()
    addPColumn.value = data
    if (addPColumn.value.condition) {
      setTimeout(() => {
        conditionRef.value.treeData = addPColumn.value.condition
      }, 0)
    }
  })
}
const handleConditionConfirm = () => {
  if (addPColumn.value) {
    findAndEdit(conditionRef.value.treeData, 'condition')
  } else {
    addPRow.value.condition = conditionRef.value.treeData
  }
  isShowCondition.value = false
  addPColumn.value = ''
  addPRow.value = ''
  console.log(headerTree.value)
  console.log(indexTree.value)
}
const findAndEdit = (res, type) => {
  console.log(res)
  const data = JSON.parse(JSON.stringify(res))
  if (type == 'del') {
    setData(headerTree.value, data, 'del')
    return
  }
  if (type == 'condition') {
    setData(headerTree.value, data, 'condition')
    return
  }
  if (data.id) {
    setData(headerTree.value, data, 'edit')
    return
  }
  if (addPColumn.value) {
    setData(headerTree.value, data, 'add')
  } else {
    headerTree.value.push({
      ...data,
      id: 'xh' + new Date().getTime(),
      parentId: 0
    })
  }
  function setData(tree, data, type) {
    tree.forEach((item, index) => {
      if (item.id == addPColumn.value.id) {
        if (type == 'add') {
          // 增
          if (!item.children) item.children = []
          item.children.push({
            ...data,
            id: 'xh' + new Date().getTime(),
            parentId: item.id
          })
        } else if (type == 'edit') {
          // 改
          item.indexName = data.indexName
          item.indexType = data.indexType
          item.content = data.content
        } else if (type == 'del') {
          // 删
          tree.splice(index, 1)
        } else if (type == 'condition') {
          // 关系
          item.condition = data
        }
      } else if (item.children) {
        setData(item.children, data, type)
      }
    })
  }
}
const handleAddRow = () => {
  addPRow.value = ''
  rowDialogVisible.value = true
}
const handleAddRowConfirm = () => {
  columnFormRef.value.validate((valid) => {
    if (valid) {
      if (addPRow.value) {
        // 改
        if (rowForm.id) {
          addPRow.value.indexName = rowForm.indexName
          addPRow.value.indexType = rowForm.indexType
        } else {
          // 增child
          if (!addPRow.value.children) addPRow.value.children = []
          addPRow.value.children.push({
            id: 'xh' + new Date().getTime(),
            parentId: addPRow.value.id,
            indexName: rowForm.indexName,
            indexType: rowForm.indexType
          })
        }
      } else {
        indexTree.value.push({
          id: 'xh' + new Date().getTime(),
          parentId: 0,
          indexName: rowForm.indexName,
          indexType: rowForm.indexType
        })
      }

      addPRow.value = ''
      rowForm.indexName = ''
      rowForm.indexType = '1'
      delete rowForm.id
      rowDialogVisible.value = false
      rowDialogVisible.value = false
    }
  })
}
const tableRowAdd = (row) => {
  addPRow.value = row
  rowDialogVisible.value = true
}
const tableRowEdit = (row) => {
  addPRow.value = row
  rowForm.id = row.id
  rowForm.indexName = row.indexName
  rowForm.indexType = row.indexType
  rowDialogVisible.value = true
}
const tableRowDel = (row) => {
  function del(tree, data) {
    tree.forEach((item, index) => {
      if (item.id == data.id) {
        tree.splice(index, 1)
      } else if (item.children) {
        del(item.children, data)
      }
    })
  }
  del(indexTree.value, row)
}
const handleAddCondition = (data) => {
  isShowCondition.value = true
  nextTick(() => {
    conditionRef.value.reset()
    addPRow.value = data
    if (addPRow.value.condition) {
      setTimeout(() => {
        conditionRef.value.treeData = addPRow.value.condition
      }, 0)
    }
  })
}
const handleSubmit = () => {
  console.log(headerTree.value)
  console.log(indexTree.value)
  const xParams = getTree(indexTree.value)
  const yParams = getTree(headerTree.value)
  console.log(xParams)
  console.log(yParams)
  const params = {
    ...form,
    dataId: dataId.value,
    x: xParams,
    y: yParams,
    headerTree: headerTree.value,
    indexTree: indexTree.value
  }
  if (route.query.id) {
    params._id = route.query.id
  }
  console.log(params)
  getStatisticsSave(params).then((res) => {
    ElMessage.success('保存成功')
    router.back()
  })
  function getTree(tree) {
    const list = []
    tree.forEach((item) => {
      const params = { ...item, condition: getCondition(item.condition) }
      if (item.children && item.children.length) {
        params.children = getTree(item.children)
      } else {
        delete item.children
      }
      list.push(params)
    })
    return list
  }

  function getCondition(condition) {
    if (condition) {
      const params = getJson(condition.children)
      console.log(params)
      return params[0]
    } else {
      return {}
    }
    function getJson(list) {
      if (list.length > 0) {
        const data = []
        list.forEach((item) => {
          if (item.type == 'condition') {
            data.push({
              type: 'connect',
              connect: item.condition,
              children: getJson(item.children)
            })
          } else if (item.type == 'field') {
            data.push({
              type: 'condition',
              field: item.value,
              operator: getOperator(item.compare),
              valueType: 'value',
              value: item.compareValue
            })
          }
        })
        return data
      }
      return {}
    }
  }
}
const getOperator = (value) => {
  switch (value) {
    case '=': {
      return 'eq'
    }
    case '!=': {
      return 'ne'
    }
    case '>': {
      return 'gt'
    }
    case '<': {
      return 'lt'
    }
    case '>=': {
      return 'gte'
    }
    case '<=': {
      return 'lte'
    }
    case 'like': {
      return 'like'
    }
    case 'not like': {
      return 'notLike'
    }
    case 'in': {
      return 'in'
    }
    case 'not in': {
      return 'notIn'
    }
    case 'isNull': {
      return 'isNull'
    }
    case 'notNull': {
      return 'notNull'
    }
    case 'startsWith': {
      return 'startsWith'
    }
    case 'endsWith': {
      return 'endsWith'
    }
    default:
      return ''
  }
}
onMounted(() => {
  if (route.query.id) {
    getStatisticsInfo(route.query.id).then((res) => {
      headerTree.value = res.data.headerTree
      indexTree.value = res.data.indexTree
      form.name = res.data.name
      form.dataId = res.data.dataId
      form.areaColumn = res.data.areaColumn
      form.openLevel = res.data.openLevel
      form._id = res.data._id
      getDataById(res.data.dataId).then((response) => {
        dataId.value = response.data._id
        conditionList.value = response.data.metadata
      })
    })
  } else {
    getNowData().then((res) => {
      dataId.value = res.data._id
      conditionList.value = res.data.metadata
    })
  }
})
</script>

<style lang="scss" scoped>
.box {
  height: calc(100% - 100px);
  overflow: auto;
}
.cursor {
  cursor: pointer;
}
.el-table {
  box-shadow: 0 0 10px #ccc;
}
:deep(.el-table) {
  --el-table-border: 1px solid #cacaca;
  --el-table-border-color: 1px solid #cacaca;
}
:deep(.el-card__body) {
  height: 100%;
}
</style>
